<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border style="width: 100%">
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="dbbottom vcenter"
              :class="{ bdtop: index === 0 }"
              v-for="(item, index) in scope.row.children"
              :key="item.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  class="vcenter"
                  :class="{ bdtop: index !== 0 }"
                  v-for="(item1, index) in item.children"
                  :key="item1.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 数据行 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色姓名"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限列表弹出层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形控件 -->
      <!--
          :data 数据来源
          :props 显示配置
          show-checkbox 显示复选框
          default-expand-all 默认展开所有树节点
          node-key="id" 设置选中为id, 而非文本
          :default-checked-keys 设置默认选中项,接收一个数组作为参数
       -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // ---------------角色列表数据---------------
      rolelist: [],
      // ---------------控制权限列表弹出层的显示与隐藏---------------
      setRightDialogVisible: false,
      // ---------------权限列表数据---------------
      rightList: [],
      // ---------------树形控件的显示配置---------------
      treeProps: {
        //  树显示的属性
        label: 'authName',
        children: 'children'
      },
      // ---------------树形控件的默认选中项参数---------------
      defKeys: [],
      // ---------------保存当前数据数据行id(备用)---------------
      roleId: undefined
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // ---------------获取角色列表---------------
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }
      this.rolelist = res.data
    },
    // ---------------删除角色权限---------------
    removeRightById (role, rightId) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        // 点击确定
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        role.children = res.data
        this.$message({
          message: '删除成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      }).catch(() => {
        // 点击删除
      })
    },
    // ---------------点击显示权限列表弹出层---------------
    async showSetRightsDialog (role) {
      const { data: res } = await this.$http.get('rights/tree')
      //   点击分配按钮时立即保存当前数据行 id(以备后面使用)
      this.roleId = role.id
      this.rightList = res.data
      this.setRightDialogVisible = true
      // 获取最后一级的id,方式1-不用递归,缺点: 在不知道层级的情况下,无法确定嵌套多少层
      /*
      role.children.forEach(item1 => {
        item1.children.forEach(item2 => {
          item2.children.forEach(item3 => {
            this.defKeys.push(item3.id)
          })
        })
      })
      */
      //   this.getLeafKey(role)
      this.getLeafKey(role, this.defKeys)
    },
    // ---------------通过递归的形式获取所有三级权限并保存---------------
    // 方式2-写简化版递归,递归过程中少传变量
    /*
    --------------核心代码-----------
      if(当前项存在children属性){
        循环当前项的children属性内容(t=>{
          调用自己(相当于回到上一步继续判断)
        })
      }else{
        将当前 id 追加到 defKeys 这个数组中
      }
    ----------------End-------------
    */
    // getLeafKey (item) {
    //   if (item.children) {
    //     item.children.forEach(t => {
    //       this.getLeafKey(t)
    //     })
    //   } else {
    //     this.defKeys.push(item.id)
    //   }
    // }
    // 方式3 标准版的递归
    getLeafKey (item, arr) {
      if (item.children) {
        item.children.forEach(t => {
          this.getLeafKey(t, arr)
        })
      } else {
        arr.push(item.id)
      }
    },
    // ---------------关闭弹出层后还原数据(避免递归数据覆盖的BUG)---------------
    setRightDialogClose () {
      this.defKeys = []
    },
    // ---------------实现权限分配功能---------------
    async saveRights () {
      const rids = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      await this.$http.post('roles/' + this.roleId + '/rights', {
        rids: rids.join(',')
      })
      this.setRightDialogVisible = false
      this.getRoleList()
      this.$message({
        message: '分配成功',
        type: 'success',
        showClose: true,
        duration: 3000
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px dashed #eee;
}

.dbbottom {
  border-bottom: 1px dashed #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
